#include "threadPool.h"
int transfile(int sockfd){
    train_t train;
    char filename[] = "file1";
    train.length = 5;//火车头
    memcpy(train.data,filename,train.length);
    int ret = send(sockfd,&train,sizeof(train.length)+train.length,MSG_NOSIGNAL);//不能写sizeof(train)
    ERROR_CHECK(ret,-1,"send");

    int fd = open(filename,O_RDWR);
    struct stat statbuf;
    fstat(fd,&statbuf);
    printf("filesize = %ld\n", statbuf.st_size);
    off_t filesize = statbuf.st_size;
    train.length = sizeof(filesize);
    memcpy(train.data,&filesize,sizeof(off_t));
    int ret2 = send(sockfd,&train,sizeof(train.length)+train.length,MSG_NOSIGNAL);//不能写sizeof(train)
    ERROR_CHECK(ret2,-1,"send");
    // 先执行ftruncate
    ftruncate(fd,filesize);
    printf("hello59\n");
    // 建立映射区
    char * p = (char *)mmap(NULL,filesize,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    off_t offset = 0;
    printf("before while 63\n");
    while(1){
        if(offset >= filesize){
            break; //发完了
        }
        if(filesize - offset > 1000){
            train.length = 1000; //剩余内容超过1000 本次只发1000
        }
        else{
            train.length = filesize - offset; //剩余内容不足1000 本次发剩下的
        }
        send(sockfd,&train.length,sizeof(train.length), MSG_NOSIGNAL);
        send(sockfd, p+offset, train.length, MSG_NOSIGNAL); //从内核态到内核态
        offset += train.length;
    }
    printf("after while 78\n");
    // 最后发一个空火车
    train.length = 0;
    send(sockfd,&train.length,sizeof(train.length),MSG_NOSIGNAL);
    // 释放映射区
    munmap(p,filesize);
    return 0;
}
